﻿#include "FrameMain.h"
#include "Utils/QPTypes.h"

#include <QWidget>
#include <QDialog>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QGridLayout>
#include <QString>
#include <QLineEdit>
#include <QApplication>
#include <QMessageBox>
#include <QPainter>
FrameMain::FrameMain(QWidget *parent )
    : QWidget{parent}
{
#if (QT_VERSION >= QT_VERSION_CHECK(6,0,0))
    resize(1000,600);
#else
    resize(900,600);
#endif
    setWindowFlags(Qt::FramelessWindowHint);
    setAttribute(Qt::WA_TranslucentBackground);
    setObjectName("FrameMain");
    QSize FixedSize(35,35);//固定尺寸，ico，btn
    
    setMouseTracking(true);
    ///
    /// \brief ConfigWidget：配置窗口由开发者自己实现并通过setConfigWidget重新赋值给ConfigWidget，
    /// 最后点击 BtnSetting 按钮显示配置窗口；
    /// 假若开发者没有setConfigWidget，对ConfigWidget空指针已做相关处理
    ///
    ConfigWidget = nullptr;

    TitleBar = new QFrame();
    TitleBar->setStyleSheet("color:white;background-color:#1E1E1E;");
    TitleBar->setFixedHeight(FixedSize.height());
    TitleBar->setAttribute(Qt::WA_Hover, true); //开启悬停事件

    LIco =new QLabel();
    LIco->setMinimumSize(FixedSize);
    LIco->setMaximumSize(FixedSize);
    LIco->setStyleSheet("padding:3px");

    LTitle =new QLabel();
    LTitle->setAttribute(Qt::WA_TranslucentBackground);
    LTitle->setAutoFillBackground(true);
    LTitle->setStyleSheet("background:transparent;");

    BtnSetting = new QToolButton();
    BtnMin = new QPushButton();
    BtnMax = new QPushButton();
    BtnClose = new QPushButton();


    BtnSetting->setIcon(QIcon(QPixmap(":/image/logo/setting3.svg")));
    BtnMin->setIcon(QIcon(QPixmap(":/image/logo/window_min1.svg")));
    BtnMax->setIcon(QIcon(QPixmap(":/image/logo/window_max1.svg")));
    //    BtnSetting->setIcon(QIcon(setSvgColor(QImage(":/image/logo/setting3.svg"),QColor("#ffffff"))));
    //    BtnMin->setIcon(QIcon(setSvgColor(QImage(":/image/logo/window_min1.svg"),QColor("#ffffff"))));
    //    BtnMax->setIcon(QIcon(setSvgColor(QImage(":/image/logo/window_max1.svg"),QColor("#ffffff"))));
    BtnClose->setIcon(QIcon(setSvgColor(QImage(":/image/logo/window_close.svg"),QColor("#1296db"))));

    //按钮，长宽一致
    BtnSetting->setFixedSize(FixedSize);
    BtnMin->setFixedSize(FixedSize);
    BtnMax->setFixedSize(FixedSize);
    BtnClose->setFixedSize(FixedSize);

    const QString BtnStyle = "border:none;outline:0px";
    LTitle->setStyleSheet(BtnStyle);
    BtnSetting->setStyleSheet(BtnStyle);
    BtnMin->setStyleSheet(BtnStyle);
    BtnMax->setStyleSheet(BtnStyle);
    BtnClose->setStyleSheet(BtnStyle);

    QHBoxLayout *hbTitle = new QHBoxLayout();

    hbTitle->addWidget(LIco);
    hbTitle->addWidget(LTitle);
    hbTitle->addWidget(BtnSetting);
    hbTitle->addWidget(BtnMin);
    hbTitle->addWidget(BtnMax);
    hbTitle->addWidget(BtnClose);
    hbTitle->setContentsMargins(0,0,0,0);
    hbTitle->setSpacing(0);
    TitleBar->setLayout(hbTitle);

    MainWidget = new QWidget();
    MainWidget->setObjectName("MainWidget");
    MainWidget->resize(this->width(),this->height()-(2*FixedSize.height()-10));
    MainWidget->setStyleSheet("#MainWidget{\
                                        background-color:#000000;\
                                        padding:0px;\
                                        margin:0px;\
                                        border:none;\
                                        outline:0px\
                                    }");

    StatBar = new QStatusBar(this);
    StatBar->setObjectName("StatBar");
    StatBar->setStyleSheet("#StatBar{\
                                background-color:#000000;\
                            }");
    StatBar->setFixedHeight(3);

    QGridLayout *Grid=new QGridLayout();
    Grid->addWidget(TitleBar);
    Grid->addWidget(MainWidget);
    Grid->addWidget(StatBar);
    Grid->setContentsMargins(0,0,0,0);
    Grid->setSpacing(0);
    setLayout(Grid);

    connect(BtnSetting,&QPushButton::released,this,&FrameMain::getDialog);
    connect(BtnMin,&QPushButton::released,this,&FrameMain::MinFrameMain);
    connect(BtnMax,&QPushButton::released,this,&FrameMain::MaxFrameMain);
    connect(BtnClose,&QPushButton::released,[=](){
#if RADIUS
            this->parentWidget()->close();
#else
            this->close();
#endif
    });
    
    MainStructor();
}

FrameMain::~FrameMain()
{

}

void FrameMain::MainStructor()
{
    this->setObjectName("FrameMain");
    this->TitleBar->setObjectName("TitleBar");
    this->LTitle->setObjectName("LTitle");
    this->LIco->setObjectName("LIco");
    this->StatBar->setObjectName("StatBar");
    this->MainWidget->setObjectName("MainWidget");
    this->BtnSetting->setObjectName("BtnSetting");
    this->BtnMin->setObjectName("BtnMin");
    this->BtnMax->setObjectName("BtnMax");
    this->BtnClose->setObjectName("BtnClose");
#if 0
    QLabel *lab =new QLabel(this);
    lab->setFixedSize(QSize(15,15));
    lab->setStyleSheet("padding:5px;background-color:green;border-radius:7px");
    QLabel *lab1 =new QLabel(this);
    lab1->setText("假装网络连接良好");
    lab1->setStyleSheet("padding:2px;color:black;font-size:12px");
    addWidgetInStatBar(lab);
    addWidgetInStatBar(lab1);
#endif
    TitleBar->installEventFilter(this); //安装事件过滤器
    BtnMax->installEventFilter(this);
    BtnMin->installEventFilter(this);
    BtnClose->installEventFilter(this);
    
    isWindowMax = false;
    m_leftButtonPressed = false;
    StatBar->show();
}

void FrameMain::addWidgetInStatBar(QWidget *widget, int stretch)
{
    StatBar->addWidget(widget,stretch);
}

void FrameMain::setConfigWidget(QWidget *conf)
{
    this->ConfigWidget = conf;
}

bool FrameMain::eventFilter(QObject * obj, QEvent * event)
{
    QMouseEvent *MEvent = static_cast<QMouseEvent*>(event);
    if(obj == BtnClose)
    {
        switch (MEvent->type()) {
        case QEvent::HoverEnter:
            BtnClose->setIcon(QIcon(setSvgColor(QImage(":/image/logo/window_close.svg"),QColor("#d81e06"))));
            break;
        case QEvent::HoverLeave:
            BtnClose->setIcon(QIcon(setSvgColor(QImage(":/image/logo/window_close.svg"),QColor("#1296db"))));
            break;
        default:
            break;
        }
    }
    if(obj == TitleBar)
    {
        switch (MEvent->type()) {
        case QEvent::MouseButtonDblClick:
#if RADIUS
            isWindowMax?this->parentWidget()->showNormal():this->parentWidget()->showMaximized();
#else
            isWindowMax?this->showNormal():this->showMaximized();
#endif
            
            break;
        case QEvent::MouseButtonPress:
            if(MEvent->buttons() & Qt::LeftButton){
                setCursor(Qt::SizeAllCursor);
#if RADIUS
                isWindowMax = this->parentWidget()->isMaximized();
#else
                isWindowMax = this->isMaximized();
#endif
                
                m_leftButtonPressed = true;
                //获得鼠标的初始位置
                startPos = MEvent->globalPos();
                //mouseStartPoint = event->pos();
                //获得窗口的初始位置
#if RADIUS
                winTopLeftPoint = this->parentWidget()->frameGeometry().topLeft();
#else
                winTopLeftPoint = this->frameGeometry().topLeft();
#endif
                
            }
            else if(MEvent->buttons() & Qt::RightButton){
                qout << "鼠标右击";
            }
            break;
        case QEvent::MouseButtonRelease:
            setCursor(Qt::ArrowCursor);
            m_leftButtonPressed = false;
            break;
        case QEvent::MouseMove:
        {    //获得鼠标移动的距离
            //QPoint distance = event->pos() - mouseStartPoint;
            //改变窗口的位置
            if(isWindowMax)
            {
                return false;
            }
            if(MEvent->buttons() & Qt::LeftButton){
                setCursor(Qt::SizeAllCursor);
                QPoint distance = MEvent->globalPos() - startPos;
#if RADIUS
                this->parentWidget()->move(winTopLeftPoint + distance);
#else
                this->move(winTopLeftPoint + distance);
#endif
                
            }          
        }
        break;
        default:
            break;
        }
    }
    return QWidget::eventFilter(obj, event);
}


void FrameMain::MaxFrameMain()
{
#if RADIUS
    Qt::WindowStates WinState = this->parentWidget()->windowState();
#else
    Qt::WindowStates WinState = this->windowState();
#endif
    
    switch(WinState){
    case Qt::WindowMaximized:
#if RADIUS
        this->parentWidget()->showNormal(); 
#else
        this->showNormal(); 
#endif
        BtnMax->setIcon(QIcon(QPixmap(":/image/logo/window_max1.svg")));
        break;
    case Qt::WindowNoState:
#if RADIUS
        this->parentWidget()->showMaximized();
#else
        this->showMaximized();
#endif 
        BtnMax->setIcon(QIcon(QPixmap(":/image/logo/window_recover.svg")));
    default:
        break;
    }
#if RADIUS
    isWindowMax =this->parentWidget()->isMaximized();
#else
    isWindowMax =this->isMaximized();
#endif
    
}

void FrameMain::MinFrameMain()
{
#if RADIUS
    this->parentWidget()->showMinimized();
#else
    this->showMinimized();
#endif
    
}

void FrameMain::isSetAppModal(bool falg)
{
    if(falg)
    {
        setWindowModality(Qt::ApplicationModal);
    }
}

void FrameMain::getDialog()
{
    if(ConfigWidget != nullptr)
    {
        ConfigWidget->show();
        return;
    }
    QMessageBox::warning(0, QString("QtPotPlayer提示"), tr("开发者并没有提供任何配置窗口给我，恕QtPotPlayer无能为力！！"));
}

void FrameMain::setMainWidget(QWidget *mainwidget)
{
    if(mainwidget != nullptr)
    {
        QGridLayout *grid = new QGridLayout();
        mainwidget->setParent(MainWidget);
        grid->addWidget(mainwidget);
        grid->setSpacing(0);
        grid->setContentsMargins(0,0,0,0);
        MainWidget->setLayout(grid);
    }
}

QPixmap FrameMain::StdIcon(int num)
{
    QStyle* style = QApplication::style();
    QIcon icon = style->standardIcon((QStyle::StandardPixmap)num);
    QPixmap m_pic = icon.pixmap(icon.actualSize(QSize(LIco->width()-9,LIco->height()-5)));//size自行调整
    return m_pic;
}

void FrameMain::setFrameTitle(const QString& Title)
{
    LTitle->setText(Title);
}

void FrameMain::setFrameIco(const QString& picture)
{
    if(picture.isEmpty())
    {
        LIco->setPixmap(StdIcon(0));
#if RADIUS
        this->parentWidget()->setWindowIcon(QIcon(StdIcon(0)));
#else
        this->setWindowIcon(QIcon(StdIcon(0)));
#endif
        
        return;
    }
    LIco->setScaledContents(true);				// 设置标签为可扩展内容
    LIco->setPixmap(QPixmap(picture));
    
#if RADIUS
    this->parentWidget()->setWindowIcon(QIcon(QPixmap(picture)));
#else
    this->setWindowIcon(QIcon(QPixmap(picture)));
#endif
}

QLabel *FrameMain::getLIcoObj()
{
    return LIco;
}
QLabel *FrameMain::getLTitleObj()
{
    return LTitle;
}

void FrameMain::setTitleBarSize(const QSize &FixedSize)
{
    BtnSetting->setFixedSize(FixedSize);

    BtnMin->setFixedSize(FixedSize);

    BtnMax->setFixedSize(FixedSize);

    BtnClose->setFixedSize(FixedSize);

    TitleBar->setFixedHeight(FixedSize.height());

    StatBar->setFixedHeight(FixedSize.height()-10);

    MainWidget->resize(this->width(),this->height()-(2*FixedSize.height()-10));
}

void FrameMain::HideStatBar(bool flag)
{
    if(flag){
        StatBar->hide();
    }
}

void FrameMain::setStatusMsg(const QString &msg)
{
    StatBar->showMessage(msg);
}

QPixmap FrameMain::setSvgColor(QImage image, QColor color)
{
    image  = image.convertToFormat(QImage::Format_RGBA8888_Premultiplied,Qt::NoFormatConversion);
    int bmpWidth = image.width();
    int bmpHeight = image.height();
    for(int i=0;i< bmpWidth;++i)
    {
        for(int j=0;j<bmpHeight;++j)
        {
            //将灰色(0~255)全部替换成设定的颜色，全透明的不替换
            QColor tempColor = image.pixelColor(i,j);
            if(tempColor.alpha() != 0)
            {
                color.setAlpha(tempColor.alpha());
                image.setPixelColor(i,j,color);
            }
        }
    }
    return QPixmap::fromImage(image);
}
